﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SharpSoft.Net
{
    using System.IO;

    /// <summary>
    /// 用于从公共服务器上获取应用信息，当前信息储存在阿里云code上。
    /// </summary>
    public class AppInfoHelper
    {
        private const string publicurl = @"https://code.aliyun.com/sharpsoft/publicdata/raw/master/data.json";

        public async static Task<AppInfoModel[]> LoadDataAsync()
        {
            string cfgfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appinfos.json");

            HttpClient hc = new HttpClient();
            hc.Timeout = TimeSpan.FromSeconds(5);
            string data = "";
            try
            {
                data = await hc.GetStringAsync(publicurl);
                using (var fs = new FileStream(cfgfile, FileMode.Create, FileAccess.Write))
                {
                    using (var sw = new StreamWriter(fs, Encoding.UTF8))
                    {
                        sw.Write(data);
                    }
                }
            }
            catch (Exception)
            {
                if (File.Exists(cfgfile))
                {
                    using (var sr = File.OpenText(cfgfile))
                    {
                        data = sr.ReadToEnd();
                    }

                }
                else
                {
                    throw new Exception("访问信息服务器失败且本地不存在信息缓存文件。");
                }
            }

            var obj = JsonConvert.DeserializeObject<AppInfoModel[]>(data);

            return obj;
        }
        /// <summary>
        /// 根据AppGuid获取App服务器地址
        /// </summary>
        /// <param name="appguid"></param>
        /// <returns></returns>
        public async static Task<string> GetServerAddress(string appguid)
        {
            var apps = await LoadDataAsync();
            foreach (var item in apps)
            {
                if (item.appguid.ToLower() == appguid.ToLower())
                {
                    return item.serveraddress;
                }
            }
            return null;
        }
    }
}
